﻿package core.net.socket {
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import core.events.CmdEvent;
	import flash.net.Socket;
	import com.adobe.serialization.json.JSON;
	public class CmdHandler extends EventDispatcher {
		
		//Socket
		private var socketClient:SocketClient = SocketClient.getInstance();
		
		//单例
		private static var instance:CmdHandler = new CmdHandler();
		public static function getInstance():CmdHandler{
			return instance;
		}
		
		public function CmdHandler() {
			socketClient.addEventListener(ProgressEvent.SOCKET_DATA,onSocketData);
		}
		
		
		public function send(cmd:SocketCmd):void{
			socketClient.send(cmd.commandString()+"<EOL>");//<EOL>为每条指令的分隔符
		}
		
		protected function onSocketData(e:ProgressEvent):void {
			//var sock:Socket = e.target as Socket;
			var strData:String = this.socketClient.read();//.readUTFBytes(sock.bytesAvailable);
			
			//根据<EOL>分割响应内容
			var cmds:Array = strData.split("<EOL>");
			for(var i=0;i<cmds.length;i++)
			{
				var str:String = cmds[i];
				if(str == "")
				{
					continue;
				}
				var exp1:RegExp = new RegExp("[\r\n]","g");
				trace("[server]:"+str.replace(exp1,""));
				if(str != null && str != ""){
					var data:Object = com.adobe.serialization.json.JSON.decode(str);
					this.dispatchEvent(new CmdEvent(CmdEvent.RESPONSE,data));
				}
			}
			
			
			
			
		}

	}
	
}
